﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using OpenSoftStore.BusinessLogic.Service;
using OpenSoftStore.BusinessLogic.Common;
using OpenSoftStore.Client.Common;
using OpenSoftStore.Orm.Model;
using System.Linq;
using OpenSoftStore.Orm.View;

namespace OpenSoftStore.Client.UIL.ManageService
{
    public partial class ServiceList : UserControl
    {
        private static ServiceList instance;
        private static ServiceLogic serviceBll = new ServiceLogic();
        private static TreeLogic treeBll = new TreeLogic();

        /// <summary>
        /// 返回一个该控件的实例。如果之前该控件已经被创建，直接返回已创建的控件。
        /// 此处采用单键模式对控件实例进行缓存，避免因界面切换重复创建和销毁对象。
        /// </summary>
        public static ServiceList Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ServiceList();
                }
                //BindDataGrid(); // 每次返回该控件的实例前，都将对DataGridView控件的数据源进行重新绑定。
                return instance;
            }
        }

        /// <summary>
        /// 私有的控件实例化方法，创建实例只能通过该控件的Instance属性实现。
        /// </summary>
        private ServiceList()
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;
            dgvService.AutoGenerateColumns = false;
            LoadGridView();
            SPACommon.SetDataGridStyle(dgvService);

            treeBll.SetTreeNode(treeBll.GetProjectTree(), tvService);
            tvService.ExpandAll();
            tvService.SelectedNode = tvService.Nodes[0];
            SPACommon.SetTreeStyle(tvService);

            tsbProvider.Visible = SysPowerManager.IsHavePower(SysPowerManager.添加项目);
            tsbUpdate.Visible = SysPowerManager.IsHavePower(SysPowerManager.修改项目信息);
            tsbDelete.Visible = SysPowerManager.IsHavePower(SysPowerManager.删除项目);
            btnTree_Add.Visible= SysPowerManager.IsHavePower(SysPowerManager.管理项目分类);
            btnTree_Update.Visible= SysPowerManager.IsHavePower(SysPowerManager.管理项目分类);
            btnTree_Delete.Visible = SysPowerManager.IsHavePower(SysPowerManager.管理项目分类);
        }

        private void tsbUpdate_Click(object sender, EventArgs e)
        {
            if (dgvService.SelectedRows.Count > 0)
            {
                string id = dgvService.SelectedRows[0].Cells["Id"].Value.ToString();
                ServiceAddWindow serviceAddWindow = new ServiceAddWindow();
                serviceAddWindow.GetService(id);
                serviceAddWindow.ShowDialog();
            }
        }

        private void tsbProvider_Click(object sender, EventArgs e)
        {
            ServiceAddWindow serviceAddWindow = new ServiceAddWindow();
            serviceAddWindow.SetTreeValue(tvService.SelectedNode.Name, tvService.SelectedNode.Text);
            serviceAddWindow.ShowDialog();
        }

        public void btnSearch_Click(object sender, EventArgs e)
        {
            string treeCode = "";
            if (tvService.SelectedNode != null)
            {
                treeCode = tvService.SelectedNode.Tag.ToString();
            }
            string whereStr = "  and T.Code like'" + treeCode + "%' and  P.Name like  '" + txtName.Text.Trim() + "%'";
            LoadGridView(whereStr);
        }

        private void ServiceList_Load(object sender, EventArgs e)
        {

        }

        public void LoadGridView(string whereStr = "")
        {
            dgvService.DataSource = serviceBll.GetServiceDataTable(whereStr);
            lblServiceCount.Text = dgvService.RowCount.ToString();
        }

        private void txtName_Load(object sender, EventArgs e)
        {

        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            if (dgvService.SelectedRows.Count == 0)
            {
                return;
            }
            if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                if (dgvService.SelectedRows.Count > 0)
                {
                    var id = dgvService.SelectedRows[0].Cells["Id"].Value.ToString();
                    var extId = dgvService.SelectedRows[0].Cells["ExtId"].Value.ToString();
                    var service = new T_Product { Id = id };
                    var productExt = new T_ProductExt { ExtId = extId };
                    var list = serviceBll.Where<T_ServiceWithProduct>(s => s.ServiceId == service.Id).ToList();
                    serviceBll.DeleteService(service, productExt, list);
                    string whereStr = string.Format(" and T.Code like '{0}%' and P.Name like '{1}%' ", tvService.SelectedNode.Tag.ToString(), txtName.Text.Trim());
                    ServiceList.Instance.LoadGridView(whereStr);
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (tvService.SelectedNode == null) return;
            TreeNode tnParent = tvService.SelectedNode;
            tvService.LabelEdit = true;
            var treeNode = new TreeNode { Text = "新子项" };

            tnParent.Nodes.Add(treeNode);
            tvService.SelectedNode = treeNode;
            treeNode.BeginEdit();
            dgvService.DataSource = null;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (tvService.SelectedNode == null) return;
            tvService.LabelEdit = true;
            tvService.SelectedNode.BeginEdit();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string treeCode = tvService.SelectedNode.Tag.ToString();
            int count = serviceBll.GetServiceDataTable(" and T.Code like '" + treeCode + "%'").Rows.Count;
            if (count > 0)
            {
                FormSysMessage.ShowMessage("该节点下仍有数据，不能删除！");
                return;
            }
            else
            {
                treeBll.Delete(tvService);
            }
        }

        private void btnSearch_Click_1(object sender, EventArgs e)
        {

        }

        private void dgvService_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            tsbUpdate_Click(null, null);
        }

        private void tvService_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (tvService.SelectedNode.Tag == null) return;
            dgvService.DataSource = null;
            string name = txtName.Text.Trim();
            string whereStr = string.Format("  and T.Code like '{0}%' and P.Name like '{1}%' ", tvService.SelectedNode.Tag.ToString(), name);
            dgvService.DataSource = serviceBll.GetServiceDataTable(whereStr);
            lblServiceCount.Text = dgvService.RowCount.ToString();
        }

        private void tvService_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (tvService.SelectedNode == null) return;
            tvService.SelectedNode.EndEdit(true);
            if (!treeBll.SaveTreeNode(tvService, sender, e, "ProjectTree"))
                FormSysMessage.ShowSuccessMsg("保存失败！");
        }

        private void btnSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSearch_Click(null, null);
            }
        }

    }
}
